package controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import service.UserService;
import tools.MyCode;
import entity.User;

/**
 * Servlet implementation class AddUserServlet
 */
@WebServlet("/AddUserServlet")
public class AddUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 设置编码格式，避免中文乱码
		request.setCharacterEncoding("utf-8");
//		通过表单提交的数据，创建User对象
		User user=new User();
		user.setLoginId(request.getParameter("username"));
		user.setPassword(request.getParameter("password"));
//		user.setTradPassWord(request.getParameter("tradPassword"));
//		user.setNickName(request.getParameter("nickname"));
//		user.setRealName(request.getParameter("realname"));
//		user.setIdentityCard(request.getParameter("identitycard"));
//		user.setTelphone(Integer.valueOf(request.getParameter("telphone")));
//		调用业务层，注册一个新用户
		UserService service=new UserService();
		int re=service.addUser(user);
//		根据返回结果，调用不同的表示层，显示结果
		if(re==MyCode.HAVE) {
			request.setAttribute("errmsg", "用户名已经存在");
			request.getRequestDispatcher("error.jsp").forward(request, response);
		}else if(re==MyCode.SUCCESS) {
			request.getRequestDispatcher("index.jsp").forward(request, response);
		}else {
			request.setAttribute("errmsg", "写入时数据库出错");
			request.getRequestDispatcher("error.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
